<template>
  <VPage class="blacklist">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm class="pt-[10px]" ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="{ platform }" v-if="formshow"> </XForm>
      </template>
      <template #toolbar_btns>
        <VButton type="primary" @click="visible = true" v-hasPermi="[userAuthList.blacklist.add]">
          <div class="dk-iconfont icon-Plus mr-[4px]"></div>
          新增
        </VButton>
        <VButton @click="handleDeleteReq" v-hasPermi="[userAuthList.blacklist.delete]">
          <div class="dk-iconfont icon-Disabled text-[red] mr-[4px]"></div>
          删除
        </VButton>
        <VButton @click="handleStatus(1)" v-hasPermi="[userAuthList.blacklist.enable]">
          <div class="dk-iconfont icon-CircleCheck text-[#3487FF] mr-[4px]"></div>
          启用
        </VButton>
        <VButton @click="handleStatus(2)" v-hasPermi="[userAuthList.blacklist.disable]">
          <div class="dk-iconfont icon-Disabled text-[red] mr-[4px]"></div>
          禁用
        </VButton>
        <VButton type="" style="margin-left: auto" @click="importVisible = true" v-hasPermi="[userAuthList.blacklist.import]">
          <div class="dk-iconfont icon-Download"></div>
          导入
        </VButton>
      </template>
    </VTable>

    <AddBlackList :id="id" v-model="visible" :disabled="disabled" :originOption="{ platform, country }" @refresh="handleRefresh" @close="handleClose" />
    <Import v-model="importVisible" />
    <Log dialog v-model="logVisible" :autoLoad="false" tag="order_blacklist" :business_id="logId" />
  </VPage>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import AddBlackList from "./components/AddBlacklist/index.vue"
import Import from "./components/Import/index.vue"
import Log from "@/components/Log/index.vue"

import { userAuthList } from "@/Auth/user.js"
import { getPlatformOptions, getCountryOption } from "@/api/public"
import { getRefundList, statusBlacklist, deleteBlacklist } from "./api"
const { proxy } = getCurrentInstance()

const model = ref({})
const id = ref()
const importVisible = ref(false)
const platform = ref({})
const country = ref({})
const disabled = ref(false)

onMounted(async () => {
  await getPlatform()
  formshow.value = true
  tableRef?.value?.updateScroll()
})

const formshow = ref(false)

const getPlatform = async () => {
  try {
    const { data } = await getPlatformOptions()
    platform.value = data.map((v) => ({ label: v.platform_name, value: v.platform_id }))

    const { data: _country } = await getCountryOption()
    country.value = _country.map((v) => ({ label: v.name, value: v.country }))
  } catch (e) {
    console.error(e)
  }
}

const publicStyle = { style: { width: "220px" } }
const fieldList = ref([
  {
    field: "id",
    placeholder: "编号 支持批量，一行一个",
    type: "textarea",
    ...publicStyle,
  },
  {
    field: "platform_id",
    type: "select",
    originField: "platform",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "平台" },
    ...publicStyle,
  },
  {
    field: "order_sn",
    placeholder: "来源订单 支持批量，一行一个",
    type: "textarea",
    ...publicStyle,
  },
  {
    field: "reason",
    placeholder: "拉黑理由 支持模糊匹配",
    ...publicStyle,
  },
  {
    field: "create_user",
    selectStyle: { width: "100px" },
    type: "cascader",
    itemProps: { placeholder: "人员" },
    style: { width: "300px" },
    select: [
      { label: "创建人", value: "creator_id" },
      { label: "更新人", value: "update_id" },
    ],
  },
  {
    field: "dateRange",
    type: "dateTimeRangeNorm",
    select: [
      { label: "创建时间", value: "create_time" },
      { label: "更新时间", value: "update_time" },
    ],
  },
])
const formOption = ref({
  inline: true,
})

const getSelectRows = () => {
  const rows = tableRef?.value.$table.getCheckboxRecords()
  if (!rows?.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return []
  }
  return rows
}

// 删除
const handleDeleteReq = () => {
  const rows = getSelectRows()
  if (!rows.length) return
  const ids = rows.map((n) => n.id)
  ElMessageBox({
    title: "提示",
    message: `确认删除选中的
        <span class='text-[#3366F1] px-[4px]'>${ids.length || 1}</span>
        条数据？`,
    dangerouslyUseHTMLString: true,
    showCancelButton: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "oms-message-confirm-button",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = "处理中.."
          await deleteBlacklist({ ids })
        } catch (e) {
          console.error(e)
        } finally {
          // 列表返回结果未处理  延时处理
          setTimeout(() => {
            instance.confirmButtonLoading = false
            done()
            handleSearch()
          }, 800)
        }
      } else {
        done()
      }
    },
  })
}
// 启用/禁用
const handleStatus = (status) => {
  const rows = getSelectRows()
  if (!rows.length) return
  const ids = rows.map((n) => n.id)
  ElMessageBox({
    title: "提示",
    message: `确认${status == 1 ? "启用" : "禁用"}选中的
        <span class='text-[#3366F1] px-[4px]'>${ids.length || 1}</span>
        条数据？`,
    dangerouslyUseHTMLString: true,
    showCancelButton: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = "处理中.."
          await statusBlacklist({ ids, status })
        } catch (e) {
          console.error(e)
        } finally {
          // 列表返回结果未处理  延时处理
          setTimeout(() => {
            done()
            instance.confirmButtonLoading = false
            handleSearch()
          }, 800)
        }
      } else {
        done()
      }
    },
  })
}

const visible = ref(false)
// 编辑
const handleEdit = (_id) => {
  id.value = _id
  visible.value = true
}
// 查看详情
const handleDetail = (_id) => {
  console.warn(_id, "##")
  id.value = _id
  disabled.value = true
  visible.value = true
}
// 保存并关闭弹窗
const handleRefresh = () => {
  tableRef?.value?.query()
}
// 关闭弹窗
const handleClose = () => {
  id.value = ""
  disabled.value = false
}
// 日志
const logVisible = ref(false)
const logId = ref("")
const handleLog = (item) => {
  logId.value = item.id
  logVisible.value = true
}

const tableRef = ref()
const handleSearch = async () => {
  tableRef?.value.query()
}
const tableOptins = reactive({
  formConfig: {
    data: {
      id: "",
      platform_id: "",
      order_sn: "",
      reason: "",
      create_user: { type: "creator_id", value: [] },
      dateRange: { type: "create_time", value: [], range: true }, // 组合+日期范围
    },
  },
  showOverflow: true,
  round: true,
  columnConfig: {
    resizable: true,
  },
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", width: 90, title: "编号", field: "id" },
    {
      title: "状态",
      field: "status_text",
      width: 100,
      slots: {
        default: ({ row }) => <VStatus value={row.status == 1} />,
      },
    },
    { title: "限制平台", width: 100, field: "platform_desc" },
    { title: "用户名称", width: 100, field: "recipient_name" },
    { title: "邮箱", width: 220, field: "recipient_email" },
    { title: "电话", width: 100, field: "recipient_phone" },
    {
      title: "收件国家/州/市",
      width: 200,
      field: "recipient_province",
      slots: {
        default: ({ row }) => {
          return (
            <div class="slot-tip">
              {row.recipient_country}
              {row.recipient_province}
              {row.recipient_city}
            </div>
          )
        },
      },
    },
    { title: "街道/门牌号", width: 200, field: "recipient_door_num" },
    { title: "详细地址", width: 200, field: "recipient_address" },
    { title: "来源订单", field: "order_sn", width: 210 },
    { title: "拉黑理由", field: "reason", width: 200 },
    { title: "创建时间", field: "create_time", width: 180 },
    {
      title: "操作",
      width: 150,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => handleDetail(row.id)} v-hasPermi={[[userAuthList.blacklist.details]]}>
                详情
              </el-button>
              <el-button link type="primary" onClick={() => handleEdit(row.id)} v-hasPermi={[[userAuthList.blacklist.edit]]}>
                编辑
              </el-button>
              <el-button link type="primary" onClick={() => handleLog(row)} v-hasPermi={[[userAuthList.blacklist.log]]}>
                日志
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    autoLoad: true, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        let params = {
          ...page,
          ...form,
          id: form.id ? handleParamsArr(form.id) : [],
          order_sn: form.order_sn ? handleParamsArr(form.order_sn) : [],
        }
        params.pageNum = params.currentPage
        return getRefundList(params)
      },
    },
  },
})
const handleParamsArr = (val = "") => {
  return val.toString().trim().length ? val.split("\n") : undefined
}
</script>
<style lang="scss"></style>
